package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.ApiCountDao;
import com.itheima.service.ApiCountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.util.*;

@Service(interfaceClass = ApiCountService.class)
@Transactional
public class ApiCountServiceImpl implements ApiCountService {


    @Autowired
    private ApiCountDao apiCountDao;

    @Override
    public void saveCount4DB(String apiName) {
        Long date = new Date().getTime();
        Map<String, Object> map = new HashMap<>();
        map.put("apiName", apiName);
        map.put("date", date);
        apiCountDao.saveApiCount4DB(map);
    }

    @Override
    public List<List> findApiCountByDate(Long startTime, Long endTime) {
        List<Map> list = apiCountDao.findApiCountByDate(startTime, endTime);
        List<List> resultList = new ArrayList<>();
        for (Map map : list) {
            ArrayList<Object> tempList = new ArrayList<>();
            tempList.add(map.get("count"));
            tempList.add(map.get("apiName"));
            resultList.add(tempList);
        }
        return resultList;
    }

    @Override
    public List<Map> findApiCount4Redis() {
        //当日0点的毫秒值
        Long start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        //当日24时的毫秒值
        Long end = start + 60 * 60 * 24 * 1000;
        return apiCountDao.findApiCount4Redis(start,end);
    }
}
